package com.ah.ajax_json;
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
@WebServlet("/TestJsonServlet")
public class TestJsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public TestJsonServlet() {
		super();
	}
	static String gson_java2Json() {
		People p = new People();
		p.setName("甘宁(gson)");
		p.setPower(87);
		Gson gson = new Gson();
		// Object → json字符串
		String json = gson.toJson(p);
		// 测试
		return json;
	}
	static String jackson_Java2Json() {
		People p = new People();
		p.setName("甘宁(jackson)");
		p.setPower(87);
		ObjectMapper mapper = new ObjectMapper();
		try {
			String json = mapper.writeValueAsString(p);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		out.println(jackson_Java2Json());
		out.flush();
		out.close();
	}
}